﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Mvc4Learn.Models.Annotations
{
    public class MaxWordsAttribute : ValidationAttribute
    {
        private int _maxLengh;

        public MaxWordsAttribute(int maxLength)
            : base(() => "{0} has too many words")
        {
            this._maxLengh = maxLength;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            //            return base.IsValid(value, validationContext);
            if (value != null)
            {
                string str = value.ToString();
                if (str.Split(' ').Length > _maxLengh)
                {
                    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
                }
            }
            return ValidationResult.Success;
        }
    }
}